const jwt = require('../utils/jwt')
const { refresh_uuid } = require('../config/config.default')
const dbApi = require('../models/db')

module.exports = async (req, res, next) => {
  let token = req.headers.authorization
  token = token ? token.split('Bearer ')[1] : null
  if (!token) {
    return res.status(400).json({
      message: 'Token does not exist'
    })
  }
  try {
    const efficienttoken = await jwt.verify(token, refresh_uuid)
    const sql = `SELECT username,nickname,avatar,intro,birthday,gender,
    arts_count as artsCount ,follows_count as followsCount,fans_count as fansCount,like_count as likeCount FROM
    users WHERE username  ='${efficienttoken.uid}'`
    const [data] = await dbApi.query(sql)
    req.user = data
    next()
  } catch (error) {
    return res.status(401).json({
      message: 'token to exceed the time limit'
    })
  }
}
